package com.zsc.boot.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.databind.ser.Serializers;
import com.sun.org.apache.xpath.internal.operations.Bool;
import com.zsc.boot.bean.User;
import com.zsc.boot.bean.request.UserLoginRequest;
import com.zsc.boot.bean.request.UserRegisterRequest;
import com.zsc.boot.common.BaseResponse;
import com.zsc.boot.common.ErrorType;
import com.zsc.boot.common.ResultResponse;
import com.zsc.boot.contant.UserContant;
import com.zsc.boot.exception.BusinessException;
import com.zsc.boot.service.UserService;
import com.zsc.boot.service.impl.UserServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.zsc.boot.contant.UserContant.ADMIN_ROLE;
import static com.zsc.boot.contant.UserContant.USER_LOGIN_STATE;

@RestController
@RequestMapping("/user")
@CrossOrigin(origins = {"http://localhost:5173"},allowCredentials = "true")
@Slf4j
public class UserController {

    @Resource
    private UserService userService;

    @Resource
    private RedisTemplate redisTemplate;


    /**
     * 注册接口
     *
     * @param userRegisterRequest
     * @return 用户id
     */
    @PostMapping("/register")
    //这里加入@RequestBody是为了与前端传过来的参数作对应
    public BaseResponse<Long> UserRegisterController(@RequestBody UserRegisterRequest userRegisterRequest){
        //需要判断前端传过来的参数是否为空
        if(userRegisterRequest == null){
            throw new BusinessException(ErrorType.NULL_ERROR);
        }
        String username = userRegisterRequest.getUsername();
        String userAccount = userRegisterRequest.getUserAccount();
        String userPassword = userRegisterRequest.getUserPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();
        if(StringUtils.isAnyBlank(username,userAccount, userPassword, checkPassword)){
            throw new BusinessException(ErrorType.NULL_ERROR);
        }
        long id = userService.UserRegister(username,userAccount, userPassword, checkPassword);
        return ResultResponse.success(id);
    }


    /**
     * 登录接口
     * @param userLoginRequest
     * @param request
     * @return 用户信息
     */
    @PostMapping("/login")
    public BaseResponse<User> UserLoginController(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request){
        //需要判断前端传过来的参数是否为空
        if(userLoginRequest == null){
            throw new BusinessException(ErrorType.NULL_ERROR);
        }
        String userAccount = userLoginRequest.getUserAccount();
        String userPassword = userLoginRequest.getUserPassword();
        if(StringUtils.isAnyBlank(userAccount, userPassword)){
            throw new BusinessException(ErrorType.PARAMS_ERROR);
        }
        User user = userService.UserLogin(userAccount, userPassword, request);
        return ResultResponse.success(user);
    }    /**


     * 注销接口
     * @param request
     * @return 用户信息
     */
    @PostMapping("/logout")
    public BaseResponse<Integer> UserLogoutController(HttpServletRequest request){
        //需要判断前端传过来的参数是否为空
        if(request == null){
            throw new BusinessException(ErrorType.NULL_ERROR);
        }

        int result = userService.UserLogout(request);
        return ResultResponse.success(result);
    }


    /**
     * 获取用户是否登录的接口（每一个用户登录后的信息都会存放在session中，所以我们需要获取从session中获取用户信息）
     * @param request
     * @return 登录后session中的user
     */
    @GetMapping("/current")
    public BaseResponse<User> GetUserCurrent(HttpServletRequest request){
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        User currentUser = (User) userObj;
        //todo 有问题
        if(currentUser == null){
            throw new BusinessException(ErrorType.NULL_ERROR);
        }
        /*
        注意：这里我们要实时更新用户的状态（所以每次执行这个接口都要去查表）
        1、从上面session中获取的uer获取其id
        2、根据这个id去查表
        */
        Long id = currentUser.getId();
        //todo 校验用户是否合法
        User user = userService.getById(id);
        User safeUser = userService.getSafeUser(user);
        return ResultResponse.success(safeUser);
    }


    /**
     * 用户管理的查询的接口
     * @param username
     * @return 查询的用户信息
     */
    @GetMapping("/search")
    public BaseResponse<List<User>> SearchUser(String username,HttpServletRequest request){
        /*判断按权限*/
        if(!userService.isAdmin(request)){
            throw new BusinessException(ErrorType.NO_AUTH);
        }

        /*查询用户信息*/
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        //判断username不为空
        if (StringUtils.isNotBlank(username)){
            queryWrapper.like("username",username);//第一个username是数据表中的字段名，第二个username是上面的形参
        }
        List<User> userList = userService.list(queryWrapper);
        //信息脱敏
        List<User> userlist = userList.stream().map(user -> {
           return userService.getSafeUser(user);
        }).collect(Collectors.toList());
        return ResultResponse.success(userlist);
    }


    /**
     * 用户管理的根据id删除的接口
     * @param id
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> DeleteUserById(long id, HttpServletRequest request){
        /*判断按权限*/
        if(!userService.isAdmin(request)){
            throw new BusinessException(ErrorType.NO_AUTH);
        }

        /*根据id删除*/
        //判断id合法
        if(id<=0){
            throw new BusinessException(ErrorType.NOT_LOGIN);
        }

        boolean result = userService.removeById(id);
        return ResultResponse.success(result);
    }


    /**
     * 根据标签搜索用户
     * @param tagList
     * @return
     */
    @GetMapping("/search/tags")
    public BaseResponse<List<User>> SearchUserByTags(@RequestParam(required = false) List<String> tagList){
        if(CollectionUtils.isEmpty(tagList)){
            throw new BusinessException(ErrorType.PARAMS_ERROR);
        }
        List<User> userList = userService.searchUserByTags(tagList);
        return ResultResponse.success(userList);
    }


    /**
     * 更新修改用户信息
     * @param user
     * @param request
     * @return
     */
    @PostMapping("/update")
        /* 前端的user页面需要修改用户的信息，那如何判断用户是否能修改呢
           1、用户只能修改自己的信息
           2、管理员可以修改任何用户的信息
        */
    public BaseResponse<Integer> update(@RequestBody User user,HttpServletRequest request){
        if(user == null){
            throw new BusinessException(ErrorType.PARAMS_ERROR);
        }
        //获取当前登录的用户信息
        User loginUser = userService.getLoginUser(request);

        //调用UserService中的更新用户的接口
        int result = userService.updateUser(user,loginUser);
        return ResultResponse.success(result);
    }

    /**
     * 主页推荐用户接口，暂时先查询出所有用户
     * @param pageSize：页面的大小
     * @param pageNum：当前页面是第几页
     * @param request
     * @return
     */
    @GetMapping("/recommend")
    public BaseResponse<Page<User>> recommendUsers( long pageSize,long pageNum, HttpServletRequest request){
        //根据不同的用户推荐不同的内容，用户根据id区分
        User loginUser = userService.getLoginUser(request);

        //因为公司中为了减少成本，会将多个项目用同一个redis，所以避免key值重复必须自定义
        String redisKey = String.format("partner:user:recommend:%s",loginUser.getId());

        ValueOperations<String,Object> valueOperations = redisTemplate.opsForValue();

        //从缓存中取到的内容直接返回到页面中
        Page<User> userPage = (Page<User>) valueOperations.get(redisKey);

        if(userPage != null){
            return ResultResponse.success(userPage);
        }
        //无缓存查数据库
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        //进行分页操作需要执行每页的大小和当前是第几页
        userPage = userService.page(new Page<>(pageNum,pageSize), queryWrapper);

        //写入缓存,将数据库中查出的userPage直接放入缓存
        try { //这里之所以用try - catch 进行捕获，是因为即使redis写入出错了，仍能查数据库返回给前端
            valueOperations.set(redisKey,userPage,1, TimeUnit.MINUTES);
        } catch (Exception e) {
            log.error("redis set key error!");
        }

        return ResultResponse.success(userPage);
    }
}

